{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c361ce2b-f769-4b6b-839a-6dd9888d5b16",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:38:49.174204Z",
     "iopub.status.busy": "2024-12-02T15:38:49.173796Z",
     "iopub.status.idle": "2024-12-02T15:38:49.182531Z",
     "shell.execute_reply": "2024-12-02T15:38:49.180432Z",
     "shell.execute_reply.started": "2024-12-02T15:38:49.174180Z"
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2788bc19-8899-43ea-8ca0-c0aeb4587983",
   "metadata": {},
   "source": [
    "### broadcast"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10baa1fb-7ce2-43a3-bbe6-8bd55e92010e",
   "metadata": {},
   "source": [
    "```\n",
    "cos_sim = F.cosine_similarity(feats[:,None,:], feats[None,:,:], dim=-1)\n",
    "```\n",
    "\n",
    "假设 feats 的原始形状是 (N, D)，其中：\n",
    "- N 是批次大小（在这里是 2 batch_size）\n",
    "- D 是特征维度\n",
    "\n",
    "通过添加 None（等同于 unsqueeze）操作：\n",
    "- feats[:,None,:] 将形状从 (N, D) 变为 (N, 1, D)\n",
    "- feats[None,:,:] 将形状从 (N, D) 变为 (1, N, D)\n",
    "\n",
    "广播\n",
    "\n",
    "当这两个张量进行运算时，PyTorch 的广播机制会将它们扩展为相同的形状：\n",
    "- (N, 1, D) → (N, N, D)\n",
    "- (1, N, D) → (N, N, D)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "98fbf721-ad5c-4f5d-b0b4-3b97ca9065de",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:42:08.403174Z",
     "iopub.status.busy": "2024-12-02T15:42:08.402753Z",
     "iopub.status.idle": "2024-12-02T15:42:08.411563Z",
     "shell.execute_reply": "2024-12-02T15:42:08.409423Z",
     "shell.execute_reply.started": "2024-12-02T15:42:08.403145Z"
    }
   },
   "outputs": [],
   "source": [
    "# 假设 feats 的形状是 (3, 2)，即 3 个样本，每个特征维度为 2\n",
    "X = torch.tensor([\n",
    "    [1, 2],  # 样本1\n",
    "    [3, 4],  # 样本2\n",
    "    [5, 6]   # 样本3\n",
    "], dtype=torch.float32)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "09ab1af8-55a5-43ed-9eb9-7d9385246821",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:42:10.142626Z",
     "iopub.status.busy": "2024-12-02T15:42:10.141960Z",
     "iopub.status.idle": "2024-12-02T15:42:10.154511Z",
     "shell.execute_reply": "2024-12-02T15:42:10.152208Z",
     "shell.execute_reply.started": "2024-12-02T15:42:10.142577Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([3, 2])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d1521eba-3cfa-42bf-a62b-b254b5538fbc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:42:11.164067Z",
     "iopub.status.busy": "2024-12-02T15:42:11.163472Z",
     "iopub.status.idle": "2024-12-02T15:42:11.182647Z",
     "shell.execute_reply": "2024-12-02T15:42:11.180286Z",
     "shell.execute_reply.started": "2024-12-02T15:42:11.164023Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1.0000, 0.9839, 0.9734],\n",
       "        [0.9839, 1.0000, 0.9987],\n",
       "        [0.9734, 0.9987, 1.0000]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cos_sim = F.cosine_similarity(X[:, None, :], X[None,:,:], dim=-1)\n",
    "cos_sim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4a3860bf-badd-4486-87e5-3624faaf546a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:43:27.145713Z",
     "iopub.status.busy": "2024-12-02T15:43:27.145058Z",
     "iopub.status.idle": "2024-12-02T15:43:27.161644Z",
     "shell.execute_reply": "2024-12-02T15:43:27.159393Z",
     "shell.execute_reply.started": "2024-12-02T15:43:27.145665Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(0.9839)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(1*3+2*4) / torch.norm(torch.tensor([1., 2.])) / torch.norm(torch.tensor([3., 4.]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "18c4d844-7cc8-4ecd-b8d7-04f34ec89a8a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:41:31.404536Z",
     "iopub.status.busy": "2024-12-02T15:41:31.403859Z",
     "iopub.status.idle": "2024-12-02T15:41:31.424728Z",
     "shell.execute_reply": "2024-12-02T15:41:31.422568Z",
     "shell.execute_reply.started": "2024-12-02T15:41:31.404487Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# feats[:,None,:] 的形状是 (3, 1, 2)：\n",
    "[\n",
    "    [[1, 2]],\n",
    "    [[3, 4]],\n",
    "    [[5, 6]]\n",
    "]\n",
    "\n",
    "# feats[None,:,:] 的形状是 (1, 3, 2)：\n",
    "[\n",
    "    [[1, 2],\n",
    "     [3, 4],\n",
    "     [5, 6]]\n",
    "]\n",
    "\n",
    "# 广播后，两个张量都变成 (3, 3, 2)：\n",
    "# 第一个张量（垂直方向重复）：\n",
    "[\n",
    "    [[1, 2], \n",
    "     [1, 2], \n",
    "     [1, 2]],\n",
    "    [[3, 4], \n",
    "     [3, 4], \n",
    "     [3, 4]],\n",
    "    [[5, 6], \n",
    "     [5, 6], \n",
    "     [5, 6]]\n",
    "]\n",
    "\n",
    "# 第二个张量（水平方向重复）：\n",
    "[\n",
    "    [[1, 2], \n",
    "     [3, 4], \n",
    "     [5, 6]],\n",
    "    [[1, 2], \n",
    "     [3, 4], \n",
    "     [5, 6]],\n",
    "    [[1, 2], \n",
    "     [3, 4], \n",
    "     [5, 6]]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a913f2e6-4bb1-4a0b-afb1-d83344094a0a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-12-02T15:51:21.822340Z",
     "iopub.status.busy": "2024-12-02T15:51:21.821069Z",
     "iopub.status.idle": "2024-12-02T15:51:21.831886Z",
     "shell.execute_reply": "2024-12-02T15:51:21.830626Z",
     "shell.execute_reply.started": "2024-12-02T15:51:21.822291Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([100])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input1 = torch.randn(100, 128)\n",
    "input2 = torch.randn(100, 128)\n",
    "output = F.cosine_similarity(input1, input2)\n",
    "output.shape"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
